<template>
  <el-dialog :title="formData.priceConfigUuid ? '修改' : '添加'" :model-value="dialog" @close="close">
    <el-form :model="formData" :rules="rules" ref="uploadForm" label-width="auto" style="padding: 0 20px" class="Dform">
      <el-form-item label="品牌：" prop="brandUuid">
        <el-select v-model="formData.brandUuid" @change="getSeriesList(true)" filterable clearable style="width: 100%"
          placeholder="请选择品牌">
          <el-option v-for="item in brandList" :key="item.brandUuid" :label="item.brandName" :value="item.brandUuid" />
        </el-select>
      </el-form-item>
      <el-form-item label="车系：" prop="seriesUuid">
        <el-select v-model="formData.seriesUuid" @change="getModelList(true)" filterable clearable style="width: 100%"
          placeholder="请选择车系">
          <el-option v-for="item in seriesList" :key="item.seriesUuid" :label="item.seriesName"
            :value="item.seriesUuid" />
        </el-select>
      </el-form-item>
      <el-form-item label="车型：" prop="modelUuid">
        <el-select v-model="formData.modelUuid" filterable clearable style="width: 100%" placeholder="请选择车型">
          <el-option v-for="item in modelList" :key="item.modelUuid" :label="item.modelName" :value="item.modelUuid" />
        </el-select>
      </el-form-item>
      <el-form-item label="车型类型：" prop="modelType">
        <el-select v-model="formData.modelType" filterable clearable style="width: 100%" placeholder="请选择车型类型">
          <el-option v-for="item in priceModelTypeMap.keys()" :key="item" :label="priceModelTypeMap.get(item)"
            :value="item" />
        </el-select>
      </el-form-item>
      <!--  -->
      <!-- <el-form-item label="车辆：" prop="carUuid">
        <el-select v-model="formData.carUuid" filterable clearable style="width: 100%" placeholder="请选择车辆">
          <el-option v-for="item in carList" :key="item.carUuid" :label="item.plateNumber + '/' + item.vin"
            :value="item.carUuid" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="价格（元）" prop="price">
        <el-input v-model="formData.price" type="number" />
      </el-form-item>
      <el-form-item label="司机价格：" prop="driverShowPrice">
        <el-input v-model="formData.driverShowPrice" />
      </el-form-item>
      <el-form-item label="价格配置名称" prop="priceConfigName">
        <el-input v-model="formData.priceConfigName" type="text" />
      </el-form-item>

      <el-form-item label="配置来源" prop="configSource">
        <el-select v-model="formData.configSource" filterable clearable style="width: 100%" placeholder="请选择配置来源">
          <el-option :label="item.partnerName" :value="item.partnerUuid" v-for="item in partnerList"
            :key="item.partnerUuid" />
        </el-select>
      </el-form-item>
      <el-form-item label="价格类型" prop="priceType">
        <el-select v-model="formData.priceType" @change="() => {
          formData.departureAddress = ''
          formData.destinationAddress = '';
        }" filterable clearable style="width: 100%" placeholder="请选择价格类型">
          <el-option :label="priceTypeMap.get(item)" :value="item" v-for="item in priceTypeMap.keys()" :key="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="包车时间(小时)" prop="hours" v-if="formData.priceType != 1">
        <el-input v-model="formData.hours" type="number" />
      </el-form-item>
      <el-form-item label="生效时间：" prop="serviceTime">
        <el-date-picker v-model="formData.serviceTime" type="datetimerange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">提交</el-button>
        <el-button v-if="!formData.priceConfigUuid" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePriceConfig, savePriceConfig } from '@/api/system'
import { brandQueryAll, selectListByBrandUuid, selectListBySeriesUuid, carQuery } from '@/api/vehicle'
import { priceTypeMap, priceModelTypeMap } from '@/config/constants'
import { partnerQuery, } from '@/api/user'

export default defineComponent({
  components: {
  },
  props: {
    dialog: {
      type: Boolean,
      default: false,
    },
    currentForm: {
      type: Object,
      default: () => { },
    },
    selectMenuList: {
      type: Array as PropType<{ title: string; id: string | number }[]>,
      default: () => [],
    },
  },
  emits: ['update:currentForm', 'update:dialog', 'refresh'],
  setup(props, context) {
    const formData = reactive(props.currentForm)
    const uploadForm = ref<any>(null)

    const brandList = ref<any>([])
    const seriesList = ref<any>([])
    const modelList = ref<any>([])
    const carList = ref<any>([])
    const partnerList = ref<any>([])

    watch(() => props.dialog,
      (val) => {
        Object.assign(formData, props.currentForm)
      }
    )

    const close = () => {
      context.emit('update:dialog', false)
      context.emit('refresh', { ...formData })
      context.emit('update:currentForm', {})
    }

    const getSeriesList = (flag = false) => {
      if (flag) {
        formData.seriesUuid = ''
        formData.modelUuid = ''
        formData.carUuid = ''
      }
      if (!formData.brandUuid) {
        return
      }
      selectListByBrandUuid({ pageNum: 1, pageSize: 100, brandUuid: formData.brandUuid }).then((res: any) => {
        seriesList.value = res.data || []
      })
    }

    const getModelList = (flag = false) => {
      if (flag) {
        formData.modelUuid = ''
        formData.carUuid = ''
      }
      if (!formData.seriesUuid) {
        return
      }
      selectListBySeriesUuid({ pageNum: 1, pageSize: 100, seriesUuid: formData.seriesUuid }).then((res: any) => {
        modelList.value = res.data || []
      })
    }
    const getCarList = () => {
      carQuery({ pageNum: 1, pageSize: 1000, modelUuid: formData.modelUuid }).then((res: any) => {
        carList.value = res.data.list || []
      })
    }
    onMounted(() => {
      brandQueryAll().then((res: any) => {
        brandList.value = res.data || []
      })
      if (formData.brandUuid) {
        getSeriesList()
      }
      // getSeriesList()
      if (formData.seriesUuid) {
        getModelList()
      }
      if (formData.effectiveStartTime && formData.effectiveEndTime) {
        formData.serviceTime = [new Date(formData.effectiveStartTime), new Date(formData.effectiveEndTime)]
      }
      // getCarList()
      partnerQuery({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
        partnerList.value = res.data.list || []
      })
    })

    const onSubmit = () => {
      uploadForm.value.validate((valid: boolean) => {
        if (valid) {

          if (formData.priceConfigUuid) {
            updatePriceConfig({
              ...formData,
              effectiveStartTime: formData.serviceTime[0],
              effectiveEndTime: formData.serviceTime[1],
            }).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('修改成功')
                close()
              }
            })
          } else {
            savePriceConfig({
              ...formData,
              effectiveStartTime: formData.serviceTime[0],
              effectiveEndTime: formData.serviceTime[1],
            }).then((res: any) => {
              if (res.code == 200) {
                ElMessage.success('添加成功')
                close()
              }
            })
          }
        } else {
          ElMessage({
            message: '验证失败',
            type: 'error',
            duration: 1000,
          })
          return false
        }
      })
    }

    const resetForm = () => {
      uploadForm.value.resetFields()
      context.emit('update:currentForm', {})
    }

    return {
      uploadForm,
      formData,
      brandList,
      seriesList,
      modelList,
      partnerList,
      carList,
      priceTypeMap,
      priceModelTypeMap,
      close,
      resetForm,
      onSubmit,
      getSeriesList,
      getModelList,
      getCarList,
      rules: {
        days: [
          { required: true, message: '请输入天数', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        priceConfigName: [
          { required: true, message: '请输入价格配置名称', trigger: 'blur' }
        ],
        driverShowPrice: [
          { required: true, message: '请输入司机价格', trigger: 'blur' }
        ],
        priceType: [
          { required: true, message: '请选择价格类型', trigger: 'blur' }
        ],
        // carUuid: [
        //   { required: true, message: '请选择车辆', trigger: 'blur' }
        // ],
        departureAddress: [
          { required: true, message: '请输入出发地', trigger: 'blur' }
        ],
        destinationAddress: [
          { required: true, message: '请输入目的地', trigger: 'blur' }
        ],
        serviceTime: [
          { required: true, message: '请选择生效时间', trigger: 'blur' }
        ],
        seriesUuid: [
          { required: true, message: '请选择车系', trigger: 'blur' }
        ],
        modelUuid: [
          { required: true, message: '请选择车型', trigger: 'blur' }
        ],
        brandUuid: [
          { required: true, message: '请选择品牌', trigger: 'blur' }
        ],
        configSource: [
          { required: true, message: '请选择配置来源', trigger: 'blur' }
        ],
        hours: [
          { required: true, message: '请输入包车时间', trigger: 'blur' }
        ],
        useCarPartner: [
          { required: true, message: '请选择用车合作方', trigger: 'blur' }
        ],
        modelType: [
          { required: true, message: '请选择车型类型', trigger: 'blur' }
        ],
      },
    }
  },
})
</script>

<style lang="scss" scoped></style>
